﻿using System;
using System.Linq;
using System.Web.Mvc;
using Kooboo.Web.Mvc.Paging;

namespace Kooboo.Web.Areas.Commerce.Controllers
{
    using System.Collections.Generic;
    using Kooboo.Commerce;
    using Kooboo.IoC;
    using Kooboo.Web.Mvc;
    using Kooboo.Globalization;
    using Kooboo.Commerce.Contexts.Brands;
    using Kooboo.Commerce.Contexts.ProductTypes;

    
    public class BrandController : ManagementController
    {
        #region Index

        public ActionResult Index(string sort)
        {
           
            var list = this.Actor
                .QueryBrands();

            if (string.IsNullOrEmpty(sort) || sort.Equals("asc"))
            {
                list = list.OrderBy(it => it.Name);
                ViewData["sort"] = "asc";
            }
            else
            {
                list = list
                    .OrderByDescending(it => it.Name);
                ViewData["sort"] = "desc";
            }


            return View(list);
        }

        public ActionResult Products(int id, int? page, int? pagesize)
        {
         
            var brand = this.Actor.QueryBrands().FirstOrDefault(i => i.Id == id);
            ViewData["Brand"] = brand;
            if (brand != null)
            {
                var list = brand.Products
                    .OrderByDescending(i => i.Id)
                    .Select(i => new ProductModel
                    {
                        Id = i.Id,
                        //SKU = i.SKU,
                        Name = i.Name,
                        //PurchasePrice = i.PurchasePrice,
                        //RetailPrice = i.RetailPrice,
                        BrandName = i.Brand.Name,
                        ProductTypeName = i.ProductType.Name,
                        //Stock = i.Stock,
                        //Hidden = i.Hidden,
                        //CanBackOrder = i.CanBackOrder
                    });



                ViewData["ProductTypes"] = brand.ProductTypes.Where(i => i.IsEnable).AsEnumerable();

                return View(list.ToPagedList(page ?? 1, pagesize ?? Configuration.PageSize));
            }

            ViewData["ProductTypes"] = this.Actor
                .QueryProductTypes()
                .Where(i => i.IsEnable)
                .AsEnumerable();

            return View(new List<ProductModel>().ToPagedList(page ?? 1, pagesize ?? Configuration.PageSize));
        }

        #endregion

        #region Create

        public ActionResult Create()
        {

            SetValidator(this.Url.Action<BrandController>(i => i.Create(null)));

            var brand = ObjectContainer.CreateInstance<IBrand>();

            ViewData["ProductTypes"] = this.Actor
                .QueryProductTypes()
                .OrderByDescending(i => i.Id)
                .ToSelectableList();

            ViewData["LogoUrl"] = brand.BuildLogoUrl();
            ViewData["UploadUrl"] = this.Url.Action<ImageController>(i => i.Upload("brand", false));

            return View(brand);
        }

        [HttpPost]
        public ActionResult Create(IBrand brand)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    this.Actor.Post(brand);

                    return this.Redirect(this.Url.Action<BrandController>(i => i.Index(null)));
                }
                catch (System.Data.DuplicateNameException)
                {
                    return Json(new { Message = "The brand name already exists.".Localize() });
                }

            }
            else
            {
                return Json(new { Message = ModelState.GetErrorMessages() });
            }

        }

        #endregion

        #region Edit

        public ActionResult Edit(int id)
        {

            var brand = this.Actor
                .QueryBrands()
                .FirstOrDefault(i => i.Id == id);

            if (brand == null)
            {
                return HttpNotFound();
            }


            ViewData["LogoUrl"] = brand.BuildLogoUrl();
            ViewData["UploadUrl"] = this.Url.Action<ImageController>(i => i.Upload("brand", false));

            ViewData["ProductTypes"] = this.Actor
                .QueryProductTypes()
                .OrderByDescending(i=>i.Id)
                .ToSelectableList(brand.ProductTypes.ToArray());

            SetValidator(this.Url.Action<BrandController>(i => i.Edit(null)));

            return View(brand);
        }

        private void SetValidator(string action)
        {
             ViewData["Validator"] = ModelClientMetadataBuilder
                .BuildFor<IBrand>(action)
                .ValidateFor(i => i.Name)
                .ValidateFor(i => i.Description)
                .ValidateFor(i => i.Logo)
                .ToMetadata();
        }

        [HttpPost]
        public ActionResult Edit(IBrand brand)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    this.Actor.Put(brand);

                    return this.Redirect(this.Url.Action<BrandController>(i=>i.Index(null)));
                }
                catch (System.Data.DuplicateNameException)
                {
                    return Json(new { Message = "The brand name already exists.".Localize() });
                }

            }
            else
            {
                return Json(new { Message = ModelState.GetErrorMessages() });
            }
        }

        #endregion

        #region Delete
        [HttpPost]
        public ActionResult Delete(IBrand brand)
        {
            this.Actor.Delete(brand);
            return Json(true);
        }

        #endregion

    }
}
